var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦？\nnode server.js 8888 这样不会吗？')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看，上面不要看 ************/

  console.log('有个傻子发请求过来啦！路径（带查询参数）为：' + pathWithQuery)

     if(path === '/index.html'){
      response.statusCode = 200
      response.setHeader('Content-Type', 'text/html;charset=utf-8')
      response.write(fs.readFileSync('./index.html')) // 这里是浏览器对请求的回应
      response.end()
     }else if(path === '/qq.js'){
      response.statusCode = 200
      response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
      response.write(fs.readFileSync('./qq.js')) // 这里是浏览器对请求的回应
      response.end()
     }else if(path === '/friends.json'){
      response.statusCode = 200
      response.setHeader('Content-Type', 'text/json;charset=utf-8')
      response.setHeader('Access-Control-Allow-Origin','http://frank.com:9999')
      console.log(request.headers['referer'])
      response.write(fs.readFileSync('./friends.json')) // 这里是浏览器对请求的回应
      response.end()
     }else if(path === '/friends.js'){
      response.statusCode = 200
      console.log(query.functionName)
      response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
      const string =fs.readFileSync("./friends.js").toString()  //从JS拿到字符串
      const data =fs.readFileSync("./friends.json").toString()  //从JSON拿到数据
      const string2 =string.replace("{{data}}",data).replace('{{xxx}}',query.callback)  //将数据写入到JS的字符串中
      response.write(string2) // 这里是浏览器对请求的回应 ，给予了新的包含数据的字符串
      response.end()
     }else{
      response.statusCode = 404
      response.setHeader('Content-Type', 'text/html;charset=utf-8')
      response.write('傻瓜，没文件啦') // 这里是浏览器对请求的回应
      response.end()
     }
   
  /******** 代码结束，下面不要看 ************/
})

server.listen(port)
console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)


